package com.nkzy.controller;

import com.nkzy.pojo.User;
import com.nkzy.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
//RestFul风格：在类中的注解@RequestMapping,加上s
@RequestMapping("/users")
public class UserController {

    @Autowired
    private UserService userService;

    // 添加用户
    @PostMapping
    public ResponseEntity<User> addUser(@RequestBody User user) {
        int result = userService.insert(user);
        if (result > 0) {
            return ResponseEntity.ok(user);
        } else {
            return ResponseEntity.badRequest().build();
        }
    }

    // 删除用户
    @DeleteMapping("/{id}")
    public ResponseEntity<Void> deleteUser(@PathVariable Long id) {
        int result = userService.deleteById(id);
        if (result > 0) {
            return ResponseEntity.noContent().build();
        } else {
            return ResponseEntity.notFound().build();
        }
    }

    // 更新用户
    @PutMapping
//    {id}是RestFul风格的使用，{id}表示点位符，表示占位符
    public ResponseEntity<User> updateUser(@RequestBody User user) {
        int result = userService.update(user);
        if (result > 0) {
            return ResponseEntity.ok(user);
        } else {
            return ResponseEntity.badRequest().build();
        }
    }

    // 根据ID查询用户
    @GetMapping("/{id}")
    public ResponseEntity<User> getUserById(@PathVariable Long id) {
        User user = userService.selectById(id);
        if (user != null) {
            return ResponseEntity.ok(user);
        } else {
            return ResponseEntity.notFound().build();
        }
    }

    // 查询所有用户
    @GetMapping
    public ResponseEntity<List<User>> listAllUsers() {
        List<User> users = userService.selectAll();
        return ResponseEntity.ok(users);
    }

    // 根据多个ID查询多个用户
    @GetMapping("/ids")
    public ResponseEntity<List<User>> listUsersByIds(@RequestParam List<Long> ids) {
        List<User> users = userService.selectByIds(ids);
        return ResponseEntity.ok(users);
    }
}
